package cn.bluemobi.platform.service.impl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import cn.bluemobi.common.core.dto.MapDto;
import cn.bluemobi.common.core.dto.Page;
import cn.bluemobi.common.core.dto.PageCondition;
import cn.bluemobi.platform.core.mybatis.PageUtils;
import cn.bluemobi.platform.entity.member.Member;
import cn.bluemobi.platform.entity.order.Address;
import cn.bluemobi.platform.entity.order.Order;
import cn.bluemobi.platform.entity.order.OrderItem;
import cn.bluemobi.platform.entity.system.SystemSetting;
import cn.bluemobi.platform.entity.system.User;
import cn.bluemobi.platform.mapper.MemberMapper;
import cn.bluemobi.platform.mapper.OrderMapper;
import cn.bluemobi.platform.mapper.PointsRebateMapper;
import cn.bluemobi.platform.mapper.SystemSettingMapper;
import cn.bluemobi.platform.service.OrderService;

/**
 * 
 * @author lvxh
 * 
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private MemberMapper memberMapper;

	@Autowired
	private SystemSettingMapper systemSettingMapper;

	@Autowired
	private PointsRebateMapper pointsRebateMapper;

	@Override
	public Page<Order> findOrders(PageCondition cond, User user) {
		Page<Order> page = PageUtils.startPage(cond);
		cond.getMap().put("merchantId", user.getMerchantId());
		page.setList(orderMapper.findOrders(cond.getMap()));
		return page;
	}

	@Override
	public Order findOrderDetail(String orderId) {
		Order order = orderMapper.findOrderDetail(orderId);
		Map<String, Object> showItems = new HashMap<String, Object>();
		if (order != null) {
			List<OrderItem> items = orderMapper.findOrderItem(orderId);
			showItems.put("orderItems", items);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String createdTime = sdf.format(order.getCreateDate()).toString();
		if (order.getPayDate() != null) {
			String paidTime = sdf.format(order.getPayDate()).toString();
			showItems.put("paidTime", paidTime);
		}
		showItems.put("createdTime", createdTime);
		order.setShowItems(showItems);
		return order;
	}

	@Override
	public List<Map<String, Object>> findLogisticsList() {
		return orderMapper.findLogisticsList();
	}

	@Override
	public MapDto confirmDelivery(String orderId, String logisticsCode,
			String logisticsNumber, User user) {
		MapDto dto = new MapDto();
		orderMapper.confirmDelivery(logisticsCode, logisticsNumber, orderId);
		return dto;
	}

	@Override
	public MapDto deleteOrder(String orderId, User user) {
		MapDto dto = new MapDto();
		orderMapper.deleteOrder(orderId);
		return dto;
	}

	@Override
	public Address findOrderAddressDetail(String orderiId) {
		Address address = null;
		address = orderMapper.findAddress(orderiId);
		if (address == null) {
			address = new Address();
		}
		return address;
	}

	public static void main(String[] args) {
		String a = "0.5";
		Double b = Double.parseDouble(a);
		System.out.println(b + b * 2 * 0.01);
	}

	@Override
	public MapDto sendReward(String orderId, String memberId, User user) {
		MapDto dto = new MapDto();
		Double franchiserRebateRate = 0d;// 经销商返现比例(%)
		Double distributorRebateRate = 0d;// 分销商返现比例(%)
		Double agentRebateRate = 0d;// 代理商返现比例(%)
		Double prefectureRebateRate = 0d;// 商品专区返现比例（%）
		// Double ordinaryRebateRate = 0d;// 普通会员返现比例(%)
		SystemSetting systemSetting = systemSettingMapper
				.findSystemSettingDetail();
		if (systemSetting == null) {
			franchiserRebateRate = 10d;
			distributorRebateRate = 10d;
			agentRebateRate = 10d;
			prefectureRebateRate = 2d;
			// ordinaryRebateRate = 10d;
		} else {
			franchiserRebateRate = Double.parseDouble(systemSetting
					.getFranchiserRebateRate());
			distributorRebateRate = Double.parseDouble(systemSetting
					.getDistributorRebateRate());
			agentRebateRate = Double.parseDouble(systemSetting
					.getAgentRebateRate());
			prefectureRebateRate = Double.parseDouble(systemSetting
					.getPrefectureRebateRate());
			// ordinaryRebateRate = Double.parseDouble(systemSetting
			// .getOrdinaryRebateRate());
		}
		// 修改是否发送奖励
		orderMapper.updateOrderIsAudit("1", orderId);
		List<OrderItem> orderItems = orderMapper.findOrderItem(orderId);
		if (!CollectionUtils.isEmpty(orderItems)) {
			for (OrderItem orderItem : orderItems) {
				Map<String, Object> memberMap = orderMapper
						.findMemberById(memberId);
				if (!CollectionUtils.isEmpty(memberMap)) {
					Double waitRebatePoints = Double.parseDouble(orderItem
							.getWaitRebatePoints());
					if (waitRebatePoints > 0) {
						Double waitRebatePoints0 = waitRebatePoints;
						if (StringUtils.equals(memberMap.get("memberLevel")
								.toString(), "1")) {
							waitRebatePoints0 = waitRebatePoints0
									+ waitRebatePoints0
									* (franchiserRebateRate * 0.01);
						}
						if (StringUtils.equals(memberMap.get("memberLevel")
								.toString(), "2")) {
							if (StringUtils.equals(orderItem.getIsPrefecture(),
									"1")) {
								waitRebatePoints0 = waitRebatePoints0
										+ waitRebatePoints0
										* (prefectureRebateRate * 0.01);
							} else {
								waitRebatePoints0 = waitRebatePoints0
										+ waitRebatePoints0
										* (distributorRebateRate * 0.01);
							}

						}
						if (StringUtils.equals(memberMap.get("memberLevel")
								.toString(), "3")) {
							if (StringUtils.equals(orderItem.getIsPrefecture(),
									"1")) {
								waitRebatePoints0 = waitRebatePoints0
										+ waitRebatePoints0
										* (prefectureRebateRate * 0.01);
							} else {
								waitRebatePoints0 = waitRebatePoints0
										+ waitRebatePoints0
										* (agentRebateRate * 0.01);
							}

						}
						orderMapper.updateWaitMemberRebatePoints(
								waitRebatePoints0.toString(), memberId);
						// 新增积分明细
						orderMapper.insertPointsDetail(memberId,
								waitRebatePoints0.toString(), "0", "购买商品获得");
						if (memberMap.get("memberId3") != null) {
							if (StringUtils.equals(memberMap
									.get("memberLevel3").toString(), "1")) {
								Double waitRebatePoints3 = 0d;
								if (StringUtils.equals(
										orderItem.getIsPrefecture(), "1")) {
									waitRebatePoints3 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (prefectureRebateRate * 0.01);
								} else {
									waitRebatePoints3 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (franchiserRebateRate * 0.01);
								}
								orderMapper.updateWaitMemberRebatePoints(
										waitRebatePoints3.toString(), memberMap
												.get("memberId3").toString());
								// 新增积分明细
								orderMapper.insertPointsDetail(
										memberMap.get("memberId3").toString(),
										waitRebatePoints3.toString(), "0",
										"经销商获得积分");
							}
						}
						if (memberMap.get("memberId2") != null) {
							if (StringUtils.equals(memberMap
									.get("memberLevel2").toString(), "1")) {
								Double waitRebatePoints2 = 0d;
								if (StringUtils.equals(
										orderItem.getIsPrefecture(), "1")) {
									waitRebatePoints2 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (prefectureRebateRate * 0.01);
								} else {
									waitRebatePoints2 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (franchiserRebateRate * 0.01);
								}
								orderMapper.updateWaitMemberRebatePoints(
										waitRebatePoints2.toString(), memberMap
												.get("memberId2").toString());
								// 新增积分明细
								orderMapper.insertPointsDetail(
										memberMap.get("memberId2").toString(),
										waitRebatePoints2.toString(), "0",
										"经销商获得积分");
							}
							if (StringUtils.equals(memberMap
									.get("memberLevel2").toString(), "2")) {
								Double waitRebatePoints2 = 0d;
								if (StringUtils.equals(
										orderItem.getIsPrefecture(), "1")) {
									waitRebatePoints2 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (prefectureRebateRate * 0.01);
								} else {
									waitRebatePoints2 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (distributorRebateRate * 0.01);
								}
								orderMapper.updateWaitMemberRebatePoints(
										waitRebatePoints2.toString(), memberMap
												.get("memberId2").toString());
								// 新增积分明细
								orderMapper.insertPointsDetail(
										memberMap.get("memberId2").toString(),
										waitRebatePoints2.toString(), "0",
										"分销商获得积分");
							}
						}
						if (memberMap.get("memberId1") != null) {
							if (StringUtils.equals(memberMap
									.get("memberLevel1").toString(), "1")) {
								Double waitRebatePoints1 = 0d;
								if (StringUtils.equals(
										orderItem.getIsPrefecture(), "1")) {
									waitRebatePoints1 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (prefectureRebateRate * 0.01);
								} else {
									waitRebatePoints1 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (franchiserRebateRate * 0.01);
								}
								orderMapper.updateWaitMemberRebatePoints(
										waitRebatePoints1.toString(), memberMap
												.get("memberId1").toString());
								// 新增积分明细
								orderMapper.insertPointsDetail(
										memberMap.get("memberId1").toString(),
										waitRebatePoints1.toString(), "0",
										"经销商获得积分");
							}
							if (StringUtils.equals(memberMap
									.get("memberLevel1").toString(), "2")) {
								Double waitRebatePoints1 = 0d;

								if (StringUtils.equals(
										orderItem.getIsPrefecture(), "1")) {
									waitRebatePoints1 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (prefectureRebateRate * 0.01);
								} else {
									waitRebatePoints1 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (distributorRebateRate * 0.01);
								}
								orderMapper.updateWaitMemberRebatePoints(
										waitRebatePoints1.toString(), memberMap
												.get("memberId1").toString());
								// 新增积分明细
								orderMapper.insertPointsDetail(
										memberMap.get("memberId1").toString(),
										waitRebatePoints1.toString(), "0",
										"分销商获得积分");
							}
							if (StringUtils.equals(memberMap
									.get("memberLevel1").toString(), "3")) {
								Double waitRebatePoints1 = 0d;
								if (StringUtils.equals(
										orderItem.getIsPrefecture(), "1")) {
									waitRebatePoints1 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (prefectureRebateRate * 0.01);
								} else {
									waitRebatePoints1 = Double
											.parseDouble(orderItem
													.getWaitRebatePoints())
											* (agentRebateRate * 0.01);
								}
								orderMapper.updateWaitMemberRebatePoints(
										waitRebatePoints1.toString(), memberMap
												.get("memberId1").toString());
								// 新增积分明细
								orderMapper.insertPointsDetail(
										memberMap.get("memberId1").toString(),
										waitRebatePoints1.toString(), "0",
										"代理商获得积分");
							}
						}
					}
				}
			}
		}
		return dto;
	}

	// private void businessMember(String orderId, String memberId) {
	// Double businessMemberMoney = 0d;// 成为商家会员（元）
	// SystemSetting systemSetting = systemSettingMapper
	// .findSystemSettingDetail();
	// if (systemSetting == null) {
	// businessMemberMoney = 100000d;
	// } else {
	// businessMemberMoney = Double.parseDouble(systemSetting
	// .getBusinessMemberMoney());
	// }
	// orderMapper.updateOrderIsAudit("1", orderId);
	// List<OrderItem> orderItems = orderMapper.findOrderItem(orderId);
	// if (!CollectionUtils.isEmpty(orderItems)) {
	// for (OrderItem orderItem : orderItems) {
	// Double waitRebatePoints = Double.parseDouble(orderItem
	// .getWaitRebatePoints());
	// if (waitRebatePoints > 0) {
	// Member member = orderMapper.findMemberById(memberId);
	// if (member != null) {
	// // 修改用户自己的待返利积分
	// orderMapper.updateWaitMemberRebatePoints(
	// waitRebatePoints.toString(), memberId);
	// // 新增积分明细
	// orderMapper.insertPointsDetail(memberId,
	// waitRebatePoints.toString(), "0", "购买商品获得");
	// if (member.getIsBusiness() == 0) {
	// // 判断自己的带返利消费金额是否达到成为商家水平
	// Double totalRebateConsumeMoney = member
	// .getTotalRebateConsumeMoney().doubleValue();
	// if (totalRebateConsumeMoney >= businessMemberMoney) {
	// // 修改用户成为商家
	// orderMapper.updateMemberIsBusiness("1", member
	// .getId().toString());
	// // 修改用户上级成为商家
	// Member parentMember = orderMapper
	// .findMemberByInviteCode(member
	// .getParentInviteCode());
	// if (parentMember != null) {
	// orderMapper.updateMemberIsBusiness("1",
	// parentMember.getId().toString());
	// }
	// } else {
	// Double teamTotalRebateConsumeMoney = member
	// .getTeamTotalRebateConsumeMoney()
	// .doubleValue();
	// if (totalRebateConsumeMoney
	// + teamTotalRebateConsumeMoney >= businessMemberMoney) {
	// // 修改用户成为商家
	// orderMapper.updateMemberIsBusiness("1",
	// member.getId().toString());
	// // 修改用户上级成为商家
	// Member parentMember = orderMapper
	// .findMemberByInviteCode(member
	// .getParentInviteCode());
	// if (parentMember != null) {
	// orderMapper
	// .updateMemberIsBusiness("1",
	// parentMember.getId()
	// .toString());
	// }
	// }
	// }
	// } else {
	// // 修改用户自己的待返利积分
	// orderMapper.updateWaitMemberRebatePoints(
	// waitRebatePoints.toString(), memberId);
	// // 新增积分明细
	// orderMapper.insertPointsDetail(memberId,
	// waitRebatePoints.toString(), "0", "购买商品获得");
	//
	// Member parentMember = orderMapper
	// .findMemberByInviteCode(member
	// .getParentInviteCode());
	// if (parentMember.getIsBusiness() == 1) {
	// Double waitBusinessRebatePoints = waitRebatePoints / 3;
	// orderMapper.updateWaitBusinessRebatePoints(
	// waitBusinessRebatePoints.toString(),
	// parentMember.getId().toString());
	// // 新增商家奖励明细
	// orderMapper.insertBusinessRewardDetail(
	// parentMember.getId().toString(),
	// waitBusinessRebatePoints, "获得下级奖励");
	// }
	// }
	// }
	// }
	// }
	// }
	// }

	// @Scheduled(cron = "0/5 * * * * ?")
	// 每天中午十二点触发
	@Scheduled(cron = "0 0 0 * * ?")
	public void cashbackScheduled() {
		System.out.println("进入返现");
		Double memberRebateRate = 0d;// 用户返利比例
		// Double businessRebateRate = 0d;// 商家返利比例
		Double goldPointsRebateRate = 0d;// 金积分返利比例(%)
		// Double silverPointsRebateRate = 0d;// 银积分返利比例(%)
		SystemSetting systemSetting = systemSettingMapper
				.findSystemSettingDetail();
		if (systemSetting == null) {
			goldPointsRebateRate = 20d;
			// silverPointsRebateRate = 80d;
			memberRebateRate = 20d;
			// businessRebateRate = 20d;
		} else {
			goldPointsRebateRate = Double.parseDouble(systemSetting
					.getGoldPointsRebateRate());
			// silverPointsRebateRate = Double.parseDouble(systemSetting
			// .getSilverPointsRebateRate());
			memberRebateRate = Double.parseDouble(systemSetting
					.getMemberRebateRate());
			// businessRebateRate = Double.parseDouble(systemSetting
			// .getBusinessRebateRate());
		}

		List<Member> memberList = memberMapper.findAllMember();
		if (!CollectionUtils.isEmpty(memberList)) {
			for (Member member : memberList) {
				Double memberCashback = member.getWaitMemberRebatePoints()
						.doubleValue() * memberRebateRate * 0.01;
				// Double businessCashback =
				// member.getWaitBusinessRebatePoints()
				// .doubleValue() * (businessRebateRate / 100);

				Double goldPoints = memberCashback
						* (goldPointsRebateRate * 0.01);
				Double silverPoints = memberCashback - goldPoints;
				memberMapper.cashback(memberCashback, 0d, goldPoints,
						silverPoints, member.getId());
				pointsRebateMapper.insertPointsRebate(
						member.getId().toString(), goldPoints.toString(),
						silverPoints.toString(), memberCashback.toString());
			}
		}
	}
}
